package cn.stylefeng.guns.modular.fi.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.fi.entity.FiCarrierFreightInfo;
import cn.stylefeng.guns.modular.fi.mapper.FiCarrierFreightInfoMapper;
import cn.stylefeng.guns.modular.fi.model.params.FiCarrierFreightInfoParam;
import cn.stylefeng.guns.modular.fi.model.params.YunFeiParam;
import cn.stylefeng.guns.modular.fi.model.result.FiCarrierFreightInfoResult;
import cn.stylefeng.guns.modular.fi.model.result.YunFeiRs;
import  cn.stylefeng.guns.modular.fi.service.FiCarrierFreightInfoService;
import cn.stylefeng.guns.modular.fi.utils.YunFeiUtils;
import cn.stylefeng.guns.modular.rest.fi.vo.FiCarrierFreightRSVo;
import cn.stylefeng.guns.modular.transport.entity.ZhuangyunMingxiTongji;
import cn.stylefeng.guns.modular.transport.mapper.TransportDispatchMapper;
import cn.stylefeng.guns.modular.transport.model.params.TransportDispatchParam;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 承运商运费对账单 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-06-21
 */
@Service
public class FiCarrierFreightInfoServiceImpl extends ServiceImpl<FiCarrierFreightInfoMapper, FiCarrierFreightInfo> implements FiCarrierFreightInfoService {


    @Resource
    private TransportDispatchMapper transportDispatchMapper;

    @Override
    public void add(FiCarrierFreightInfoParam param){
        FiCarrierFreightInfo entity = getEntity(param);
        this.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addByCarrier(FiCarrierFreightInfoParam param) {
        TransportDispatchParam q = new TransportDispatchParam();
        q.setOperateId(param.getOperateId());
        q.setCarrierId(param.getCarrierId());
        String times = "";
        if (ToolUtil.isNotEmpty(param.getStartDt()) && ToolUtil.isNotEmpty(param.getEndDt())) {
            times = "'" + DateUtil.DateFormat(param.getStartDt(),"yyyy-MM-dd") + "' and '" + DateUtil.DateFormat(param.getEndDt() ,"yyyy-MM-dd")+ "'";
        }
        List<ZhuangyunMingxiTongji> yunFeis = this.transportDispatchMapper.getYunFeiByCarrier(q, times, param.getOperateId());
        FiCarrierFreightInfo insertObj = null;
        List<FiCarrierFreightInfo> saveObj = new ArrayList<>();
        for(ZhuangyunMingxiTongji obj : yunFeis){
            insertObj = new FiCarrierFreightInfo();
            insertObj.setOperateName(param.getOperateName());
            insertObj.setOperateId(param.getOperateId());
            insertObj.setCarrierName(param.getCarrierName());
            insertObj.setCarrierId(param.getCarrierId());
            insertObj.setDeliverId(param.getDeliverId());
            insertObj.setDeptId(param.getDeptId());
            insertObj.setCreateUser(param.getCreateUser());
            insertObj.setStat("暂存");
            insertObj.setCarrierUserCode(param.getCarrierUserCode());
            insertObj.setLineName(obj.getLineName());
            insertObj.setLineId(obj.getLineId());
            insertObj.setCreateTime(new Date());
            insertObj.setStartDt(param.getStartDt());
            insertObj.setEndDt(param.getEndDt());
            if(ToolUtil.isNotEmpty(obj.getMileageTraveled())) {
                BigDecimal mileageTraveled = new BigDecimal(obj.getMileageTraveled());
                insertObj.setKilometer(mileageTraveled.setScale(2, BigDecimal.ROUND_HALF_DOWN));
            }
            if(ToolUtil.isNotEmpty(obj.getFreightMoney())) {
                BigDecimal freightMoney = new BigDecimal(obj.getFreightMoney());
                insertObj.setFreightMoney(freightMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN));
            }
            if(ToolUtil.isNotEmpty(obj.getToovolume())) {
                BigDecimal toovolume = new BigDecimal(obj.getToovolume());
                insertObj.setSumVol(toovolume.setScale(2, BigDecimal.ROUND_HALF_DOWN));
            }
            if(ToolUtil.isNotEmpty(obj.getPieceNumber())) {
                BigDecimal pieceNumber = new BigDecimal(obj.getPieceNumber());
                insertObj.setSumNum(pieceNumber.setScale(2, BigDecimal.ROUND_HALF_DOWN));
            }
            if(ToolUtil.isNotEmpty(obj.getLoadingMoney())) {
                BigDecimal loadingMoney = new BigDecimal(obj.getLoadingMoney());
                insertObj.setLoadingMoney(loadingMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN));
            }
            //总费用
            insertObj.setSumMoney(YunFeiUtils.getSumMoney(insertObj));
            saveObj.add(insertObj);
        }
        this.saveBatch(saveObj);
    }

    @Override
    public void delete(FiCarrierFreightInfoParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(FiCarrierFreightInfoParam param){
        FiCarrierFreightInfo oldEntity = getOldEntity(param);
        FiCarrierFreightInfo newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public FiCarrierFreightInfoResult findBySpec(FiCarrierFreightInfoParam param){
        return null;
    }

    @Override
    public List<FiCarrierFreightInfoResult> findListBySpec(FiCarrierFreightInfoParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(FiCarrierFreightInfoParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getYunFei(YunFeiParam param) {
        TransportDispatchParam q1 = new TransportDispatchParam();
        q1.setLineId(param.getLineId());
        q1.setOperateId(param.getOperateId());
        String times = "";
        if(ToolUtil.isEmpty(param.getStartDt())){
            param.setStartDt( DateUtil.getDate());
        }
        if(ToolUtil.isEmpty(param.getEndDt())){
            param.setEndDt( DateUtil.getDate());
        }
        if (ToolUtil.isNotEmpty(param.getStartDt()) && ToolUtil.isNotEmpty(param.getEndDt())) {
            times = "'" + param.getStartDt() + "' and '" + param.getEndDt() + "'";
        }
        List<ZhuangyunMingxiTongji> yunFeis = this.transportDispatchMapper.getYunFei(q1, times, param.getOperateId());
        YunFeiRs yunFeiRs = new YunFeiRs();
        for(ZhuangyunMingxiTongji obj : yunFeis){
            //总个数
            if(ToolUtil.isNotEmpty(obj.getPieceNumber())) {
                BigDecimal pieceNumber = new BigDecimal(obj.getPieceNumber());
                yunFeiRs.setSumNum(yunFeiRs.getSumVol().add(pieceNumber.setScale(2, BigDecimal.ROUND_HALF_DOWN)));
            }
            //总体积
            if(ToolUtil.isNotEmpty(obj.getToovolume())) {
                BigDecimal toovolume = new BigDecimal(obj.getToovolume());
                yunFeiRs.setSumVol(yunFeiRs.getSumVol().add(toovolume.setScale(4, BigDecimal.ROUND_HALF_DOWN)));
            }
            //总里程
            if(ToolUtil.isNotEmpty(obj.getMileageTraveled())) {
                BigDecimal mileageTraveled = new BigDecimal(obj.getMileageTraveled());
                yunFeiRs.setKilometer(yunFeiRs.getKilometer().add(mileageTraveled.setScale(2, BigDecimal.ROUND_HALF_DOWN)));
            }
            //总费用
            if(ToolUtil.isNotEmpty(obj.getFreightMoney())) {
                BigDecimal freightMoney = new BigDecimal(obj.getFreightMoney());
                yunFeiRs.setFreightMoney(yunFeiRs.getFreightMoney().add(freightMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN)));
            }
            //总装车费
            if(ToolUtil.isNotEmpty(obj.getLoadingMoney())) {
                BigDecimal loadingMoney = new BigDecimal(obj.getLoadingMoney());
                yunFeiRs.setLoadingMoney(yunFeiRs.getLoadingMoney().add(loadingMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN)));
            }
        }
        return ResponseData.success(yunFeiRs);
    }

    @Override
    public List<FiCarrierFreightRSVo> getCarrierFreightList(FiCarrierFreightInfoParam param) {
        List<FiCarrierFreightInfoResult> fiCarrierFreightInfoResults = this.baseMapper.carrierFreightList(param);
        List<FiCarrierFreightRSVo> rs = new ArrayList<FiCarrierFreightRSVo>();
        Map<String,List<FiCarrierFreightInfoResult>> fiCarrierFreightMap = new HashMap<String,List<FiCarrierFreightInfoResult>>();
        List<FiCarrierFreightInfoResult> ls = null;
        for(FiCarrierFreightInfoResult obj : fiCarrierFreightInfoResults){
            String key = obj.getOperateId()+obj.getStartDt()+obj.getEndDt();
            if(fiCarrierFreightMap.get(key) == null){
                ls = new ArrayList<>();
                ls.add(obj);
                fiCarrierFreightMap.put(key, ls);
            }else{
                fiCarrierFreightMap.get(key).add(obj);
            }
        }

        FiCarrierFreightRSVo fiCarrierFreightRSVo = null;
        for(String key : fiCarrierFreightMap.keySet()){
            fiCarrierFreightRSVo = new FiCarrierFreightRSVo();
            fiCarrierFreightRSVo.setOperateId(fiCarrierFreightMap.get(key).get(0).getOperateId());
            fiCarrierFreightRSVo.setOperateName(fiCarrierFreightMap.get(key).get(0).getOperateName());
            fiCarrierFreightRSVo.setStartDt(fiCarrierFreightMap.get(key).get(0).getStartDt());
            fiCarrierFreightRSVo.setEndDt(fiCarrierFreightMap.get(key).get(0).getEndDt());
            for(FiCarrierFreightInfoResult obj : fiCarrierFreightMap.get(key)){
                // 总数量
                if(obj.getSumNum() != null){
                    fiCarrierFreightRSVo.setKilometerAll(fiCarrierFreightRSVo.getKilometerAll().add(obj.getKilometer()));
                }

                // 总数量
                if(obj.getSumNum() != null){
                    fiCarrierFreightRSVo.setSumNumAll(fiCarrierFreightRSVo.getSumNumAll().add(obj.getSumNum()));
                }

                // 总体积
                if(obj.getSumVol() != null) {
                    fiCarrierFreightRSVo.setSumVolAll(fiCarrierFreightRSVo.getSumVolAll().add(obj.getSumVol()));
                }
                // 运费
                if(obj.getFreightMoney() != null){
                    fiCarrierFreightRSVo.setFreightMoneyAll(fiCarrierFreightRSVo.getFreightMoneyAll().add(obj.getFreightMoney()));
                }

                // 总费用
                if(obj.getSumMoney() != null){
                    fiCarrierFreightRSVo.setSumMoneyAll(fiCarrierFreightRSVo.getSumMoneyAll().add(obj.getSumMoney()));
                }

                // 装车费
                if(obj.getLoadingMoney() != null){
                    fiCarrierFreightRSVo.setLoadingMoneyAll(fiCarrierFreightRSVo.getLoadingMoneyAll().add(obj.getLoadingMoney()));
                }

                // 客诉
                if(obj.getCustComplaint() != null){
                    fiCarrierFreightRSVo.setCustComplaintAll(fiCarrierFreightRSVo.getCustComplaintAll().add(obj.getCustComplaint()));
                }

                // 其他罚款
                if(obj.getOtherFines() != null){
                    fiCarrierFreightRSVo.setOtherFinesAll(fiCarrierFreightRSVo.getOtherFinesAll().add(obj.getOtherFines()));
                }
                // 其他补贴
                if(obj.getOtherSubsidie() != null){
                    fiCarrierFreightRSVo.setOtherSubsidieAll(fiCarrierFreightRSVo.getOtherSubsidieAll().add(obj.getOtherSubsidie()));
                }
            }
            fiCarrierFreightRSVo.setItems(fiCarrierFreightMap.get(key));
            rs.add(fiCarrierFreightRSVo);
        }

        return rs;
    }

    @Override
    public int updateByids(List<String> list) {
        return this.baseMapper.updateByids(list);
    }

    @Override
    public int idxStatIsOk(List<String> list) {
        return this.baseMapper.idxStatIsOk(list);
    }

    private Serializable getKey(FiCarrierFreightInfoParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private FiCarrierFreightInfo getOldEntity(FiCarrierFreightInfoParam param) {
        return this.getById(getKey(param));
    }

    private FiCarrierFreightInfo getEntity(FiCarrierFreightInfoParam param) {
        FiCarrierFreightInfo entity = new FiCarrierFreightInfo();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }



}
